import React, { useEffect, useState, useCallback } from 'react';
import { 
  Form, Input, Button, Space, Switch, Avatar, message, Card, 
  Layout, Row, Col, Typography, Tag, Pagination, Divider 
} from 'antd';
import { PlusOutlined, SearchOutlined, EditOutlined, EyeOutlined } from '@ant-design/icons';
import { AddKK } from '../setmeal/addSetmeal';
import { EditKK } from '../setmeal/editSetmeal';
import type { Isetmeal } from '../types/setmeal';
import http from '../api/http';
import { imgBaseURL } from '../api/baseURL';
import '../Subscribe/index.css';
import { SubscribeModal } from '../checkitem/findex';
import { Fcheckitem } from './fcheckitem';

const { Content } = Layout;
const { Title, Text } = Typography;

interface PaginationParams {
  current: number;
  pageSize: number;
  total: number;
}

// 优化后的卡片样式：增强立体层次、交互反馈和视觉重点
const antdStyles = {
  container: {
    minHeight: '100vh',
    padding: '24px',
    background: '#f0f2f5',
  },
  pageHeader: {
    marginBottom: '16px',
  },
  searchCard: {
    marginBottom: '24px',
    background: '#fff',
    borderRadius: '12px', // 统一圆角风格
    boxShadow: '0 2px 8px rgba(0, 0, 0, 0.05)',
  },
  // 1. 卡片容器核心优化
  packageCard: {
    transition: 'all 0.3s cubic-bezier(0.4, 0, 0.2, 1)', // 丝滑过渡
    cursor: 'pointer',
    height: '100%',
    display: 'flex',
    flexDirection: 'column',
    borderRadius: '12px', // 现代感圆角
    overflow: 'hidden', // 内容裁剪防溢出
    border: '1px solid #f0f0f0',
    background: '#fff',
    position: 'relative', // 用于状态开关定位
  },
  // 2. Hover交互效果
  packageCardHover: {
    boxShadow: '0 8px 24px rgba(0, 0, 0, 0.08)', // 柔和阴影
    transform: 'translateY(-4px)', // 悬浮上移
    borderColor: '#e6f7ff', // 主题色边框过渡
  },
  // 3. 选中状态强化
  packageCardSelected: {
    borderColor: '#1890ff',
    boxShadow: '0 4px 16px rgba(24, 144, 255, 0.15)', // 主题色阴影
  },
  // 4. 卡片顶部渐变条（视觉点睛）
  cardTopBar: {
    height: '4px',
    width: '100%',
    background: 'linear-gradient(90deg, #1890ff 0%, #40a9ff 100%)', // 主题渐变
  },
  cardContent: {
    flex: 1,
    display: 'flex',
    flexDirection: 'column',
    alignItems: 'center',
    textAlign: 'center',
    padding: '20px 16px', // 增加内边距，避免内容拥挤
  },
  avatar: {
    size: 'large',
    shape: 'circle' as const,
    marginBottom: '16px',
    border: '2px solid #f5f5f5', // 头像加边框，增强层次
  },
  nameText: {
    fontWeight: 500,
    marginBottom: '8px',
    whiteSpace: 'nowrap',
    overflow: 'hidden',
    textOverflow: 'ellipsis',
    width: '100%',
    fontSize: '15px', // 增大名称字体，突出重点
  },
  infoRow: {
    width: '100%',
    display: 'flex',
    justifyContent: 'space-between',
    marginBottom: '6px',
    fontSize: '12px',
    color: '#666', // 次要信息降色，突出重点
  },
  // 5. 价格标签优化（更醒目）
  priceTag: {
    marginTop: '8px',
    marginBottom: '12px',
    fontSize: '14px',
    padding: '4px 12px',
    fontWeight: 500,
    borderRadius: '20px', // 圆形标签更柔和
  },
  actionArea: {
    display: 'flex',
    justifyContent: 'center',
    gap: '8px',
    marginTop: 'auto',
    padding: '12px 16px', // 增加上下内边距
    borderTop: '1px solid #f0f0f0',
    width: '100%',
  },
  pagination: {
    marginTop: '32px', // 增加间距，避免与卡片拥挤
    textAlign: 'center',
  },
  detailCard: {
    marginTop: '32px',
    borderRadius: '12px',
    boxShadow: '0 2px 8px rgba(0, 0, 0, 0.05)',
  },
  // 空状态容器样式
  emptyCard: {
    borderRadius: '12px',
    border: '1px dashed #e0e0e0',
    background: '#fff',
  }
};

export default function Subscribe() {
  // 状态管理（保持原有逻辑不变）
  const [selectedRowId, setSelectedRowId] = useState<number | undefined>();
  const [currentPackageId, setCurrentPackageId] = useState<number>();
  const [modalVisible, setModalVisible] = useState(false);
  const [pagination, setPagination] = useState<PaginationParams>({
    current: 1,
    pageSize: 6,
    total: 0,
  });
  const [data, setdata] = useState<Array<Isetmeal>>([]);
  const [form] = Form.useForm();
  const [name, setName] = useState('');
  const [zj, setZj] = useState('');

  // 弹窗确认回调（保持原有逻辑不变）
  const handleModalConfirm = (selectedIds: number[], totalPrice: number, packageId?: number) => {
    console.log('选中项：', selectedIds, '总价：', totalPrice);
    setModalVisible(false);
  };

  // 搜索接口（保持原有逻辑不变）
  const search = useCallback(() => {
    http.getList<Isetmeal>("Setmeal", {
      name,
      zj,
      page: pagination.current,
      size: pagination.pageSize
    }).then(res => {
      setdata(res.data);
      setPagination(prev => ({
        ...prev,
        total: res.count,
        current: res.page || prev.current,
      }));
    })
  }, [name, zj, pagination.current, pagination.pageSize])

  // 初始加载（保持原有逻辑不变）
  useEffect(() => {
    search();
  }, [search])

  // 状态切换（保持原有逻辑不变）
  const handleStatusChange = (id: number, checked: boolean, e: React.MouseEvent) => {
    e.stopPropagation();
    setdata(prevData => 
      prevData.map(item => 
        item.id === id ? { ...item, status: checked ? 1 : 0 } : item
      )
    );
    http.put("Setmeal/zt", { id, status: checked ? 1 : 0 }).then(
      res => {
        if (res.code === '1') {
          message.success(res.msg);
        }
      }
    );
  };

  // 分页变化（保持原有逻辑不变）
  const handlePaginationChange = (page: number, pageSize: number) => {
    setPagination({
      ...pagination,
      current: page,
      pageSize: pageSize,
    });
  };

  // 卡片点击事件（保持原有逻辑不变）
  const handleCardClick = (record: Isetmeal) => {
    setSelectedRowId(record.id);
  };

  // 打开检查项弹窗（保持原有逻辑不变）
  const openModalWithId = (id: number, e: React.MouseEvent) => {
    e.stopPropagation();
    setCurrentPackageId(id);
    setModalVisible(true);
  };

  return (
    <Layout style={antdStyles.container}>
      <Content>
        {/* 页面标题 */}
        <div style={antdStyles.pageHeader}>
          <Title level={2}>套餐管理</Title>
        </div>

        {/* 搜索区域 */}
        <Card style={antdStyles.searchCard}>
          <Form
            form={form}
            layout="inline"
            onFinish={() => search()}
            initialValues={{ name: '', zj: '' }}
          >
            <Form.Item name="name" label="套餐名称" labelCol={{ span: 8 }} wrapperCol={{ span: 16 }}>
              <Input
                placeholder="请输入套餐名称"
                onChange={(e) => setName(e.target.value)}
                style={{ borderRadius: '6px' }}
              />
            </Form.Item>

            <Form.Item name="zj" label="助记名" labelCol={{ span: 8 }} wrapperCol={{ span: 16 }}>
              <Input
                placeholder="请输入助记名"
                onChange={(e) => setZj(e.target.value)}
                style={{ borderRadius: '6px' }}
              />
            </Form.Item>

            <Form.Item>
              <Space>
                <Button 
                  type="primary" 
                  htmlType="submit" 
                  icon={<SearchOutlined />}
                  style={{ borderRadius: '6px' }}
                >
                  搜索
                </Button>
                <AddKK 
                  gx={search} 
                  icon={<PlusOutlined />}
                />
              </Space>
            </Form.Item>
          </Form>
        </Card>

        {/* 套餐列表：优化后卡片布局 */}
        <Title level={4}>套餐列表</Title>
        <Divider style={{ margin: '16px 0' }} />
        
        {data.length > 0 ? (
          <Row gutter={[24, 24]}> {/* 增大间距，避免卡片拥挤 */}
            {data.map((item) => (
              <Col xs={24} sm={12} md={8} lg={6} xl={4} key={item.id}>
                <Card
                  style={{
                    ...antdStyles.packageCard,
                    ...(selectedRowId === item.id ? antdStyles.packageCardSelected : {})
                  }}
                  hoverable={false} // 关闭antd默认hover，用自定义效果
                  onClick={() => handleCardClick(item)}
                  // 自定义hover交互：更丝滑的状态切换
                  onMouseEnter={(e) => {
                    const target = e.currentTarget as HTMLElement;
                    target.style.boxShadow = antdStyles.packageCardHover.boxShadow;
                    target.style.transform = antdStyles.packageCardHover.transform;
                    target.style.borderColor = antdStyles.packageCardHover.borderColor;
                  }}
                  onMouseLeave={(e) => {
                    const target = e.currentTarget as HTMLElement;
                    target.style.boxShadow = '';
                    target.style.transform = '';
                    target.style.borderColor = selectedRowId === item.id 
                      ? antdStyles.packageCardSelected.borderColor 
                      : '#f0f0f0';
                  }}
                >
                  {/* 新增：卡片顶部渐变条 */}
                  <div style={antdStyles.cardTopBar} />
                  
                  <div style={antdStyles.cardContent}>
                    {/* 套餐图片：增加边框层次 */}
                    <Avatar
                      size={antdStyles.avatar.size}
                      shape={antdStyles.avatar.shape}
                      src={item.img ? `${imgBaseURL}${item.img}` : undefined}
                      alt={item.name}
                      style={antdStyles.avatar}
                    />
                    
                    {/* 套餐名称：放大字体突出重点 */}
                    <Text style={antdStyles.nameText}>{item.name}</Text>
                    
                    {/* 套餐信息：次要信息降色处理 */}
                    <div style={antdStyles.infoRow}>
                      <Text type="secondary">编号:</Text>
                      <Text>{item.code || '-'}</Text>
                    </div>
                    
                    <div style={antdStyles.infoRow}>
                      <Text type="secondary">性别:</Text>
                      <Text>{item.sex || '不限'}</Text>
                    </div>
                    
                    <div style={antdStyles.infoRow}>
                      <Text type="secondary">年龄:</Text>
                      <Text>{item.minage || 0}-{item.maxage || '无'}岁</Text>
                    </div>
                    
                    {/* 价格标签：放大加粗，更醒目 */}
                    <Tag color="orange" style={antdStyles.priceTag}>
                      ¥{item.price?.toFixed(2) || '0.00'}
                    </Tag>
                    
                    {/* 状态开关：移到右上角，避免遮挡内容 */}
                    <div style={{ 
                      position: 'absolute', 
                      top: '12px', 
                      right: '12px' 
                    }}>
                      <Switch
                        checked={item.status === 1}
                        checkedChildren="启用"
                        unCheckedChildren="禁用"
                        onChange={(checked) => handleStatusChange(item.id, checked, event as React.MouseEvent)}
                        size="small"
                       
                      />
                    </div>
                  </div>
                  
                  {/* 操作区域：增加内边距，更美观 */}
                  <div style={antdStyles.actionArea}>
                    <EditKK 
                      data={item} 
                      gx={search}
                      icon={<EditOutlined />}
                      size="small"
                      onClick={(e) => e.stopPropagation()}
                    />
                    <Button
                      type="primary"
                      size="small"
                      icon={<EyeOutlined />}
                      onClick={(e) => openModalWithId(item.id, e)}
                      style={{ borderRadius: '6px' }}
                    >
                      检查项
                    </Button>
                  </div>
                </Card>
              </Col>
            ))}
          </Row>
        ) : (
          // 优化后空状态：增加图标和引导文案
          <Card style={antdStyles.emptyCard}>
            <div style={{ textAlign: 'center', padding: '64px 0' }}>
              <div style={{ 
                fontSize: '48px', 
                color: '#e0e0e0', 
                marginBottom: '16px' 
              }}>
                📦
              </div>
              <Text type="secondary" style={{ fontSize: '14px' }}>
                暂无套餐数据
              </Text>
              <div style={{ marginTop: '8px' }}>
                <Text type="secondary" style={{ fontSize: '12px' }}>
                  可尝试调整搜索条件或点击"新增套餐"创建
                </Text>
              </div>
            </div>
          </Card>
        )}

        {/* 分页控件 */}
        {pagination.total > 0 && (
          <div style={antdStyles.pagination}>
            <Pagination
              current={pagination.current}
              pageSize={pagination.pageSize}
              total={pagination.total}
              onChange={handlePaginationChange}
              showSizeChanger
              showQuickJumper
              showTotal={(total) => `共 ${total} 条记录`}
              pageSizeOptions={['8', '16', '24']}
              style={{ borderRadius: '6px' }}
            />
          </div>
        )}

        {/* 详情卡片 */}
        <Card style={antdStyles.detailCard}>
          <Title level={4}>套餐详情</Title>
          <Divider style={{ margin: '16px 0' }} />
          {selectedRowId ? (
            <Fcheckitem selectedId={selectedRowId} />
          ) : (
            <Text type="secondary" style={{ padding: '24px 0', display: 'inline-block' }}>
              请点击上方套餐卡片查看详情
            </Text>
          )}
        </Card>

        {/* 检查项弹窗 */}
        <SubscribeModal
          visible={modalVisible}
          onClose={() => setModalVisible(false)}
          onConfirm={handleModalConfirm}
          packageId={currentPackageId}
          ff={search}
        />
      </Content>
    </Layout>
  );
}